package com.sakuracard.stepdemo;

import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@MapperScan("com.sakuracard.stepdemo.mapper")
@Configuration
public class MyBatisConfigurer {
  private static final Logger logger = LoggerFactory.getLogger(MyBatisConfigurer.class);
  private static final String[] MAPPER_XML_PATH = new String[]{
      "classpath:mapper/*.xml"
  };

  @Bean
  public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);

    var configuration = new org.apache.ibatis.session.Configuration();
    configuration.setMapUnderscoreToCamelCase(true);
    configuration.setLogImpl(Slf4jImpl.class);
    configuration.setCallSettersOnNulls(true);

    bean.setConfiguration(configuration);
    bean.setMapperLocations(this.getMapperLocations());

    return bean;
  }

  private Resource[] getMapperLocations() {
    ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
    List<Resource> resources = new ArrayList<>();
    for (String mapperLocation : MAPPER_XML_PATH) {
      try {
        Resource[] mappers = resourceResolver.getResources(mapperLocation);
        resources.addAll(Arrays.asList(mappers));
      } catch (IOException e) {
        logger.error("get mybatis mapper location error: " + mapperLocation, e);
      }
    }
    return resources.toArray(new Resource[0]);
  }
}
